/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysRolePermission服务层
	/// </summary>
    public class SysRolePermissionService: ISysRolePermissionService
    {
        private readonly ISysRolePermissionRepository _repository;
        private readonly ISysPermissionRepository _perRepository;

        public SysRolePermissionService(ISysRolePermissionRepository repository,ISysPermissionRepository sysPermissionRepository)
        {
            _perRepository = sysPermissionRepository;
            _repository = repository;
        }

        [Transaction]
        public async Task<IApiResult> Add(List<string> list, string roleId)
        {
            //删除出当前角色所有的权限
            await _repository.DeleteAsync(roleId, "sysrolepermission", "roleid");
            List<SysRolePermissionEntity> list_add = new List<SysRolePermissionEntity>();
            foreach(var item in list)
            {
                var data = new SysRolePermissionEntity();
                data.RoleId = roleId;
                data.PermissionId = item;
                list_add.Add(data);
            }
            //批量插入
            var res= await _repository.InsertAsync(list_add);
            return ApiResult.Ok();
        }

        public async Task<IApiResult> QueryPermission(string roleId,int platform)
        {
            var list =new List<PermissionTreeModel>();
            list = await _perRepository.GetAllPermission();
            var list_permission = await _repository.GetPermissionByRoleId(roleId);
            for(var i = 0; i < list.Count; i++)
            {
               if(list_permission.Any(a => a == list[i].Id))
                {
                    list[i].CheckArr = "1";
                }
            }
            if(platform==0)
            return ApiResult.Ok(list.Where(a => a.Platform == 0));
            else
                return ApiResult.Ok(list.Where(a => a.Platform ==1));
        }
    }
}